package com.catty.provide.check;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;

import com.catty.connect.message.handle.DefaultMessageHandler;
import com.catty.connect.minaconnect.MinaClientConnector;

public class ServiceRegularlyBook {

	private static ServiceRegularlyBook heartBeat;
	
	private static final String CONFIG_SERVER_ADDRESS = "127.0.0.1";
	
	private static final int CONFIG_SERVER_PORT = 9002;
	
	private ServiceRegularlyBook(){
	
	}
	
	public synchronized static ServiceRegularlyBook getServiceRegularlyHeartBeatInstance(){
		
		if(heartBeat==null){
			heartBeat = new ServiceRegularlyBook();
		}
		return heartBeat;
	}
	
	public void startRegularHeartBeat(){
		Thread beatThread = new Thread(
				new Runnable(){
					public void run(){
						while(true){
							MinaClientConnector configClient = MinaClientConnector.getInstances(CONFIG_SERVER_ADDRESS,
									CONFIG_SERVER_PORT,
									new DefaultMessageHandler());
							String configCenterInfo = connectConfigServerWithClosure(configClient.getSession(),
							getHeartBeatInfo());
							try {
								Thread.sleep(10000);
							} catch (InterruptedException e) {
								System.out.println("Interrupted:"+configCenterInfo);
							}
						}
					}
				}
				);
		beatThread.start();
	}
	
	private String getHeartBeatInfo(){
		try {
			return InetAddress.getLocalHost().getHostAddress()+":ok";
		} catch (UnknownHostException e) {
			return "ok";
		}
	}
	
	private String connectConfigServerWithClosure(IoSession session,String serverPublishInfo) { 
		
		String returnInfo="";
		session.getConfig().setUseReadOperation(true);

		if (session != null && session.isConnected()) { 
			 try { 
				 WriteFuture wFuture = session.write(serverPublishInfo); 
				 wFuture.awaitUninterruptibly();
				 if (wFuture.isWritten()) {
					 ReadFuture readFuture = session.read();
					 readFuture.awaitUninterruptibly(); 
					 session.getConfig().setUseReadOperation(false);
					 returnInfo = (String) readFuture.getMessage();
				 }
				 return returnInfo; 
			 } catch (Exception ex) { 
				 throw new IllegalStateException(ex); 
			 } 
		 } 
		 return returnInfo; 
}
}
